package com.dragee.modules.work.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.work.dao.CompetitionProjectDao;
import com.dragee.modules.work.entity.CompetitionProjectEntity;
import com.dragee.modules.work.service.CompetitionProjectService;
import com.dragee.utils.StringUtils;
import com.dragee.utils.WrapperUtil;
import com.dragee.utils.excel.CommonListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("competitionProjectService")
public class CompetitionProjectServiceImpl extends ServiceImpl<CompetitionProjectDao, CompetitionProjectEntity> implements CompetitionProjectService {


    @Resource
    private CompetitionProjectDao competitionProjectDao;
    @Autowired
    private CompetitionProjectService competitionProjectService;

    private String business = "competitionProject";

    private static String competitionId;
    /**
    * 列表
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        int limit = params.get(CommonConstants.LIMIT) == null
                ?CommonConstants.LIMIT_SIZE:Integer.parseInt(params.get(CommonConstants.LIMIT).toString());
        int start = params.get(CommonConstants.START) == null
                ?CommonConstants.START_SIZE:Integer.parseInt(params.get(CommonConstants.START).toString());
        QueryWrapper<CompetitionProjectEntity> wrapper =
                WrapperUtil.getWrapper(business, params, CompetitionProjectEntity.class);
        IPage<CompetitionProjectEntity> page = new Page<>(start, limit);
        page = baseMapper.selectPage(page, wrapper.select());
        return new PageUtils(page);
    }

    @Override
    public List<CompetitionProjectEntity> getProjectByCompetition(String competitionId) {
        List<CompetitionProjectEntity> projects
                = list(new QueryWrapper<CompetitionProjectEntity>()
                .eq("competitionId", competitionId)
                .orderByDesc("sort"));
        return projects;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R importProject(MultipartFile file, String competitionId) throws IOException {
        CompetitionProjectServiceImpl.competitionId = competitionId;
        //填充对应词典 sex: (1:男, 2:女)
        Map<String, Map<String,Object>> map = new HashMap<>();
        //解析器
        CommonListener<CompetitionProjectEntity> commonListener
                = new CommonListener<>(map, CompetitionProjectEntity.class,this::excelBatch);
        EasyExcel.read(file.getInputStream())
                .head(CompetitionProjectEntity.class)
                .registerReadListener(commonListener)
                .sheet()
                .doRead();
        List<String> msgList = commonListener.getMsgList();
        if(msgList.size()>0){
            return R.error(StringUtils.join(msgList,","));
        }
        return R.ok();
    }

    /** 导入执行入库方法
     * @param datas
     * @return
     */
    private boolean excelBatch (List<CompetitionProjectEntity> datas) {
        Object obj = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int i = 0; i < datas.size(); i++) {
            CompetitionProjectEntity data = datas.get(i);
            int count = count(new QueryWrapper<CompetitionProjectEntity>().eq("competitionId", competitionId)
                    .eq("name", data.getName())
                    .eq("type", data.getType()));
            if (count > 0) {
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(obj);
                throw new BusinessException(String.format("导入异常: 第%s行,项目大类[%s],名称[%s]已存在", i+2, data.getType(), data.getName()));
            }
            data.setCompetitionId(CompetitionProjectServiceImpl.competitionId);
            competitionProjectService.saveOrUpdate(data);
        }
        return true;
    }
}